<?php
namespace app\shop\model;
use app\common\logic\FlashSaleLogic;
use app\common\logic\GroupBuyLogic;
use think\Model;
class Cart extends Model {
    protected $table = 'slzd_sh_cart';
    //自定义初始化
    protected static function init()
    {
        //TODO:自定义的初始化
    }
    public function promGoods()
    {
        return $this->hasOne('PromGoods', 'id', 'prom_id')->cache(true,10);
    }

    public function goods()
    {
        return $this->hasOne('Goods', 'goods_id', 'goods_id')->cache(true,10);
    }

    public function getSpecKeyNameArrAttr($value, $data)
    {
        if ($data['spec_key_name']) {
            $specKeyNameArr = explode(' ', $data['spec_key_name']);
            return $specKeyNameArr;
        } else {
            return [];
        }
    }
    //获取购物车列表
    public function getCartData($data){
        if($data['prom_type'] >0){
            $res = $this->table('slzd_sh_cart a')
            ->join('slzd_sh_spec_goods_price b','a.spec_key = b.key')
            ->where('user_id',$data['user_id'])
            ->where('a.prom_type',$data['prom_type'])
            ->where('a.goods_id',$data['goods_id'])
            ->where('b.item_id',$data['item_id'])
            ->find();
        }else{
            if($data['item_id']>0){
                $res = $this->table('slzd_sh_cart a')
                ->join('slzd_sh_spec_goods_price b','a.spec_key = b.key')
                ->where('user_id',$data['user_id'])
                ->where('a.prom_type',$data['prom_type'])
                ->where('a.goods_id',$data['goods_id'])
                ->where('a.goods_num','>',0)
                ->where('b.item_id',$data['item_id'])
                ->find();
            }else{
                $res = $this->table('slzd_sh_cart a')
                // ->join('slzd_sh_spec_goods_price b','a.spec_key = b.key')
                ->where('user_id',$data['user_id'])
                ->where('a.prom_type',$data['prom_type'])
                ->where('a.goods_id',$data['goods_id'])
                ->find();
            }
            
        }
        return $res;
    }
    //获取购物车所有商品
    public function getAllCartData($data){
            $res = $this->table('slzd_sh_cart a')
            ->join('slzd_sh_goods b','a.goods_id = b.goods_id')
            ->where('user_id',$data['user_id'])
            ->where('a.seller_id',$data['seller_id'])
            ->where('a.goods_num','gt',0)
            ->field('id,a.goods_name,a.goods_id,a.market_price,shop_price,goods_num,spec_key,spec_key_name,original_img,store_count')
            ->select();
            // echo $this->getLastSql();exit;
            foreach ($res as $key => &$value) {
                $value['goods_price'] = $value['shop_price'];
                if($value['original_img']){
                    $value['original_img'] = config('shopimg').$value['original_img'];
                }else{
                    $value['original_img'] = config('shopimg').'/public/upload/10971515042539.jpg';
                }
            }
        return $res;
    }

    public function getSellerDetail($seller_id){
       $res = $this->table('slzd_sh_admin')
        ->field('shop_name')
        ->where('admin_id',$seller_id)
        ->find();
        return $res['shop_name'];
    }
    //多商户购物车列表 获取购物车列表    暂时不用
    // public function getCartListData($data,$page,$orll_page){
    //         $where['user_id'] = $data['user_id'];
    //         if(!empty($data['seller_id'])){
    //             $where['a.seller_id'] = $data['seller_id'];
    //         }
    //         $list['row'] = $this->table('slzd_sh_cart a')
    //         ->join('slzd_sh_goods c','a.goods_id= c.goods_id')
    //         ->join('slzd_sh_admin d','a.seller_id= d.admin_id')
    //         ->where($where)
    //         ->where('goods_num','egt',1)
    //         ->page($page,$orll_page)
    //         ->select();
    //         $count = $this->table('slzd_sh_cart a')
    //         ->join('slzd_sh_goods c','a.goods_id= c.goods_id')
    //         ->join('slzd_sh_admin d','a.seller_id= d.admin_id')
    //         ->where($where)
    //         ->where('goods_num','egt',1)
    //         ->page($page,$orll_page)
    //         ->count();
    //         $list['page'] = $page;
    //         $list['count'] = ceil($count/$orll_page);
    //         $arr = [];
    //         $list['row'] = $this->array_val_chunk($list['row']);
    //             foreach ($list['row'] as $key => &$value) {
    //            //  $value = $value['seller_id'];
    //          }
    //     return $list;
    // }
    //获取购物车列表
    public function getCartListData1($data,$page,$orll_page){
        $where = " user_id = '{$data['user_id']}' ";
        if(!empty($data['seller_id'])){
            $where .= " AND a.seller_id = '{$data['seller_id']}'";
        }
        $res = [];
        $res1 = [];
        $res2 = [];
        $sql1 = <<<sql
        SELECT
            id,a.goods_name,a.goods_id,shop_price,goods_num,spec_key,spec_key_name,original_img,b.store_count, b.price shop_price,a.item_id
        FROM
            slzd_sh_cart a 
        LEFT JOIN   
            slzd_sh_spec_goods_price b on a.item_id = b.item_id
        LEFT JOIN   
            slzd_sh_goods c on c.goods_id = b.goods_id
        WHERE
            $where and a.item_id > 0 and goods_num > 0
sql;
        $res1 = $this->query($sql1);
        $sql2 = <<<sql
        SELECT
            id,a.goods_name,a.goods_id,shop_price,goods_num,spec_key,spec_key_name,original_img,store_count,item_id
        FROM
            slzd_sh_cart a 
        LEFT JOIN   
            slzd_sh_goods b on a.goods_id = b.goods_id
        WHERE
            $where and a.item_id = 0 and goods_num > 0
sql;
        $res2 = $this->query($sql2);
        $list['row'] = array_merge($res1,$res2);
        array_multisort(array_column($list['row'],'id'),SORT_DESC,$list['row']);
        $list['page'] = $page;
        $count = count($list['row']);
        $list['row'] = array_slice($list['row'],($page-1)*$orll_page,$page*$orll_page);
        $list['count'] = ceil($count/$orll_page);
        return $list;
        // $where['user_id'] = $data['user_id'];
        // $where['a.seller_id'] = $data['seller_id'];
        // $list['row'] = $this->table('slzd_sh_cart a')
        //     // ->field('id,a.goods_name,a.goods_id,a.market_price,shop_price,goods_num,spec_key,spec_key_name,original_img,store_count')
        //     // ->join('slzd_sh_goods c','a.goods_id= c.goods_id')
        //     // ->join('slzd_sh_admin d','a.seller_id= d.admin_id')
        //     ->where($where)
        //     ->where('goods_num','egt',1)
        //     ->page($page,$orll_page)
        //     ->group('a.goods_id')
        //     ->select();
        //     echo $this->getLastSql();
        // $count = $this->table('slzd_sh_cart a')
        //     ->join('slzd_sh_goods c','a.goods_id= c.goods_id')
        //     ->join('slzd_sh_admin d','a.seller_id= d.admin_id')
        //     ->where($where)
        //     ->where('goods_num','egt',1)
        //     ->group('a.goods_id')
        //     ->page($page,$orll_page)
        //     ->count();
        // $list['page'] = $page;
        // $list['count'] = ceil($count/$orll_page);
        // $arr = [];
        // // $list['row'] = $this->array_val_chunk($list['row']);
        // foreach ($list['row'] as $key => &$value) {
        //     $value['goods_price'] = $value['shop_price'];
        //     if($value['original_img']){
        //         $value['original_img'] = config('shopimg').$value['original_img'];
        //     }else{
        //         $value['original_img'] = config('shopimg').'/public/upload/10971515042539.jpg';
        //     }
        // }
        // return $list;
    }
        //获取购物车列表
    public function getCartListData($data){
        $where = " user_id = '{$data['user_id']}' ";
        if(!empty($data['seller_id'])){
            $where .= " AND a.seller_id = '{$data['seller_id']}'";
        }
        $res = [];
        $res1 = [];
        $res2 = [];
        $sql1 = <<<sql
        SELECT
            id,a.goods_name,a.goods_id,shop_price,goods_num,spec_key,spec_key_name,original_img,b.store_count, b.price shop_price,a.item_id,c.cat_id
        FROM
            slzd_sh_cart a 
        LEFT JOIN   
            slzd_sh_spec_goods_price b on a.item_id = b.item_id
        LEFT JOIN   
            slzd_sh_goods c on c.goods_id = b.goods_id
        WHERE
            $where and a.item_id > 0 and goods_num > 0
sql;
        $res1 = $this->query($sql1);
        $sql2 = <<<sql
        SELECT
            id,a.goods_name,a.goods_id,shop_price,goods_num,spec_key,spec_key_name,original_img,store_count,item_id,b.cat_id
        FROM
            slzd_sh_cart a 
        LEFT JOIN   
            slzd_sh_goods b on a.goods_id = b.goods_id
        WHERE
            $where and a.item_id = 0 and goods_num > 0
sql;
        $res2 = $this->query($sql2);
        $list = array_merge($res1,$res2);
        array_multisort(array_column($list,'id'),SORT_DESC,$list);
        return $list;
    }

    /**
     * [getClearCartData 清空购物车]
     * @param  [array] $data [description]
     * @return [boolean]       [description]
     */
    public function getClearCartData($data){
        $where['user_id'] = $data['user_id'];
        $where['seller_id'] = $data['seller_id'];
        $cartData = $this->table('slzd_sh_cart')
            ->where($where)
            ->where('goods_num','egt',1)
            ->select();
            if($cartData){
                foreach ($cartData as $key => $value) {
                    $cartData = $this->table('slzd_sh_cart')->where('id',$value['id'])->delete();
                }
                // $cartData = $this->table('slzd_sh_cart')
                // ->where($where)
                // ->where('goods_num','egt',1)
                // ->select();
                // echo $this->getLastSql();
                // dump($cartData);
                // exit;
                return $cartData;
            }
            return false;
    }
    public function array_val_chunk($array){
        $result = [];
        foreach ($array as $key => $value) {
            $result[$value['shop_name']][] = $value;
        }
        $ret = [];
        //这里把简直转成了数字的，方便同意处理
        foreach ($result as $key => $value) {
            array_push($ret, $value);
        }
        return $result;
    }

    //获取购物车总金额和总数量
    public function getCountCartData($data){
        $where = " user_id = '{$data['user_id']}' ";
        if(!empty($data['seller_id'])){
            $where .= " AND a.seller_id = '{$data['seller_id']}'";
        }
        $res = [];
        $res1 = [];
        $res2 = [];
            $sql1 = <<<sql
        SELECT
            sum(b.price*a.goods_num) price,sum(a.goods_num) num
        FROM
            slzd_sh_cart a 
        LEFT JOIN   
            slzd_sh_spec_goods_price b on a.item_id = b.item_id
        WHERE
            $where and a.item_id > 0
sql;
        $res1 = $this->query($sql1);
            $sql2 = <<<sql
        SELECT
            sum(b.shop_price*a.goods_num) price,sum(a.goods_num) num
        FROM
            slzd_sh_cart a 
        LEFT JOIN   
            slzd_sh_goods b on a.goods_id = b.goods_id
        WHERE
            $where and a.item_id = 0
sql;
        $res2 = $this->query($sql2);
        $res = array_merge($res1,$res2);
        $res = comm_sumarrs($res);
        return [$res];
    }

    /**
     * 商品优惠总额
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getGoodsFeeAttr($value, $data)
    {
        return $data['goods_num'] * $data['member_goods_price'];
    }
    /**
     * 商品总额
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getTotalFeeAttr($value, $data)
    {
        return $data['goods_num'] * $data['goods_price'];
    }
    /**
     * 商品总额优惠
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getCutFeeAttr($value, $data)
    {
        return round(($data['goods_num'] * ($data['goods_price'] - $data['member_goods_price'])), 2);
    }

    /**
     * 限购数量
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getLimitNumAttr($value, $data)
    {
        $spec_goods_price = null;
        $goods = Goods::get($data['goods_id'], '', 20);
        //有规格
        if ($data['spec_key']) {
            $spec_goods_price = SpecGoodsPrice::get(['goods_id'=>$data['goods_id'],'key' => $data['spec_key']]);
            if ($data['prom_type'] == 1) {
                $FlashSaleLogic = new FlashSaleLogic($goods, $spec_goods_price);
                $limitNum = $FlashSaleLogic->getUserFlashResidueGoodsNum($data['user_id']);
            } else if ($data['prom_type'] == 2) {
                $groupBuyLogic = new GroupBuyLogic($goods, $spec_goods_price);
                $limitNum = $groupBuyLogic->getPromotionSurplus();//团购剩余库存
            } else {
                $limitNum = $spec_goods_price['store_count'];
            }
        }else{
            //没有规格
            if ($data['prom_type'] == 1) {
                $FlashSaleLogic = new FlashSaleLogic($goods, null);
                $limitNum = $FlashSaleLogic->getUserFlashResidueGoodsNum($data['user_id']);
            } else if ($data['prom_type'] == 2) {
                $groupBuyLogic = new GroupBuyLogic($goods, null);
                $limitNum = $groupBuyLogic->getPromotionSurplus();//团购剩余库存
            } else {
                $limitNum = $goods['store_count'];
            }
        }
        return $limitNum;
    }
}